package com.example.contextcube.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.contextcube.R;
import com.example.contextcube.db.DictionaryDatabaseHelper;
import com.example.contextcube.model.Word;
import com.example.contextcube.util.FavoriteManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 最近查询适配器
 */
public class RecentQueryAdapter extends RecyclerView.Adapter<RecentQueryAdapter.ViewHolder> implements FavoriteManager.FavoriteChangeListener {
    private List<Word> recentQueries = new ArrayList<>();
    private OnItemClickListener listener;
    private WordAdapter.OnFavoriteClickListener favoriteListener;
    private DictionaryDatabaseHelper dbHelper;
    private FavoriteManager favoriteManager;

    public interface OnItemClickListener {
        void onItemClick(Word word);
    }

    public RecentQueryAdapter(OnItemClickListener listener) {
        this.listener = listener;
        this.favoriteManager = FavoriteManager.getInstance();
        this.favoriteManager.addListener(this);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_word_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Word word = recentQueries.get(position);
        
        // 设置单词文本
        holder.wordText.setText(word.getWord());

        
        // 设置中文释义
        holder.definitionText.setText(word.getTranslation());
        
        // 从FavoriteManager获取最新的收藏状态
        boolean isFavorited = favoriteManager.isFavorited(word.getWord());
        word.setFavorite(isFavorited);
        
        // 设置收藏状态
        updateFavoriteButton(holder, word);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(word);
            }
        });
        
        // 设置收藏按钮点击事件
        holder.favoriteButton.setOnClickListener(v -> {
            // 切换收藏状态
            boolean newFavoriteState = !word.isFavorite();
            word.setFavorite(newFavoriteState);
            
            // 更新UI
            updateFavoriteButton(holder, word);
            
            // 通过FavoriteManager更新收藏状态
            favoriteManager.toggleFavorite(word.getWord(), newFavoriteState);
            
            // 通知回调
            if (favoriteListener != null) {
                favoriteListener.onFavoriteClick(word, newFavoriteState);
            }
        });
    }
    
    /**
     * 更新收藏按钮的状态
     */
    private void updateFavoriteButton(ViewHolder holder, Word word) {
        // 根据收藏状态设置图标
        if (word.isFavorite()) {
            holder.favoriteButton.setImageResource(R.drawable.ic_favorite);
        } else {
            holder.favoriteButton.setImageResource(R.drawable.ic_favorite_border);
        }
    }

    @Override
    public int getItemCount() {
        return recentQueries != null ? recentQueries.size() : 0;
    }
    
    /**
     * 更新最近查询列表
     */
    public void setRecentQueries(List<Word> recentQueries) {
        this.recentQueries = recentQueries != null ? recentQueries : new ArrayList<>();
        
        // 更新收藏状态
        for (Word word : this.recentQueries) {
            word.setFavorite(favoriteManager.isFavorited(word.getWord()));
        }
        
        notifyDataSetChanged();
    }
    
    /**
     * 设置收藏点击监听器
     */
    public void setOnFavoriteClickListener(WordAdapter.OnFavoriteClickListener listener) {
        this.favoriteListener = listener;
    }
    
    /**
     * 设置数据库助手
     */
    public void setDatabaseHelper(DictionaryDatabaseHelper dbHelper) {
        this.dbHelper = dbHelper;
        
        // 确保FavoriteManager已设置数据库
        if (favoriteManager != null && dbHelper != null) {
            favoriteManager.setDatabaseHelper(dbHelper);
            // 强制刷新收藏状态
            favoriteManager.loadAllFavorites();
        }
    }
    
    /**
     * FavoriteManager回调：当收藏状态变化时更新UI
     */
    @Override
    public void onFavoriteChanged(String wordStr, boolean isFavorite) {
        // 查找列表中是否有相同的单词，并更新其状态
        for (int i = 0; i < recentQueries.size(); i++) {
            Word word = recentQueries.get(i);
            if (word.getWord().equals(wordStr)) {
                word.setFavorite(isFavorite);
                notifyItemChanged(i);
                break;
            }
        }
    }
    
    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        // 移除监听器避免内存泄漏
        favoriteManager.removeListener(this);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView wordText;
        TextView phoneticText;
        TextView definitionText;
        ImageButton favoriteButton;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            wordText = itemView.findViewById(R.id.word_text);
            phoneticText = itemView.findViewById(R.id.phonetic_text);
            definitionText = itemView.findViewById(R.id.definition_text);
            favoriteButton = itemView.findViewById(R.id.favorite_button);
        }
    }
} 